package cs236369.webserver;
import java.util.TreeMap;
import org.apache.http.HttpResponse;


public class SessionRepository {
	private final TreeMap<Long,Session> rep = new TreeMap<Long,Session>();
	private long maxID = 1; //:)
	private final String cookieName;
	
	
	public SessionRepository(String cookieName) {
		this.cookieName = cookieName;
	}
	
	/**
	 * 0 will create a new session
	 * @param id
	 * @return
	 */
	public Session getSession(long id) {
		Session $;
		synchronized(rep) {
			$ = rep.get(new Long(id));

			if($ == null) {
				$ = new Session(maxID+1);
				maxID++;
				rep.put(new Long(maxID), $);
			}
		}
		return $;
	}
		
	public class Session {
		private final TreeMap<String,Object> m = new TreeMap<String,Object>();
		public final long id;
		
		Session(long id) {
			this.id = id;
		}

		public synchronized void set(String name, Object value) {
			m.put(name, value);
		}
		
		public synchronized Object get(String name) {
			return m.get(name);
		}
		
		public synchronized void invalidate() {
			synchronized (rep) {
				rep.remove(new Long(id));
			}
		}
		
		public synchronized void format (HttpResponse resp) {
			resp.addHeader("Set-Cookie", " "+cookieName+"="+Long.toString(id));
		}
	}
}
